import React, { useEffect } from "react";
import { constantRoutes, routesList } from "./routes/index";
import { useLocation, Navigate } from "react-router-dom";
import store from "@/redux/index";
import { getToken } from "@/utils/auth";
import { isRelogin } from "@/utils/request";
import NProgress from "@/utils/nprogress";
import { searchRoute } from "@/utils/common";
import { setRoutes, featRoute } from "@/redux/modules/permission";
// 路由守卫
export const AuthRouter = (props: { children: JSX.Element }) => {
  NProgress.start();

  if (getToken() && !isRelogin.show) {
    isRelogin.show = true;
    store
      .dispatch(featRoute())
      .then((res) => {
        localStorage.setItem("routers", JSON.stringify(res.payload));
        store.dispatch(setRoutes(res.payload));
      })
      .catch((err) => {});
  }

  const { pathname } = useLocation();
  const routes = getToken() ? constantRoutes : routesList;
  const route = searchRoute(pathname, routes);
  // console.log('route ------', route)
  NProgress.done();
  if (!route?.meta?.requiresAuth) return props.children;

  // 判断是否有token
  if (!getToken()) return <Navigate to="/login" replace />;

  NProgress.done();
  // 当前账号有权限返回，正常访问页面
  return props.children;
};

export default AuthRouter;
